package com.brandongogetap.stickyheaders.demo;

import com.brandongogetap.stickyheaders.model.ItemModel;
import com.brandongogetap.stickyheaders.tools.Utils;
import com.brandongogetap.stickyheaders.ultimateprovider.EventTransmissionListener;
import com.brandongogetap.stickyheaders.ultimateprovider.UltimateProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;

import java.util.List;

public class MainAbilitySlice extends AbilitySlice implements EventTransmissionListener {

    private ListContainer mListContainer;
    private DependentLayout mFloatGroupLayout;
    private List<ItemModel> mModelList;
    private Text mTvTitle;
    private UltimateProvider mUltimateProvider;
    private boolean mHasHeader = false;
    private boolean mIsRemoveItem = false;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
    }

    public void initView() {
        mModelList = Utils.demoList();
        mFloatGroupLayout = (DependentLayout) findComponentById(ResourceTable.Id_floatGroupLayout);
        mFloatGroupLayout.setClickedListener(component -> {

        });
        mTvTitle = (Text) findComponentById(ResourceTable.Id_tv_title);

        Image arrowImage = (Image) findComponentById(ResourceTable.Id_arrow_image);
        arrowImage.setClickedListener(component -> {
            jumpAbility();
        });

        mListContainer = (ListContainer) findComponentById(ResourceTable.Id_listView);
        mUltimateProvider = new UltimateProvider<>(mModelList, getContext());
        mUltimateProvider.setEventTransmissionListener(this::onEventTransmission);
        mListContainer.setItemProvider(mUltimateProvider);
        mListContainer.setScrolledListener(new MyScrolledListener());

        Button visibilityBtn = (Button) findComponentById(ResourceTable.Id_visibility_button);
        visibilityBtn.setClickedListener(component -> {
            int visibility = mListContainer.getVisibility() == Component.VISIBLE ? Component.HIDE : Component.VISIBLE;
            mListContainer.setVisibility(visibility);
            if (visibility == Component.VISIBLE && mHasHeader) {
                setHeaderVisibility(visibility);
            } else {
                setHeaderVisibility(Component.HIDE);
            }
        });

        //要放在初始后
        if (mModelList.size() > 0) {
            mTvTitle.setText(mModelList.get(0).getTitle());
            ShapeElement element = new ShapeElement();
            RgbColor rgbColor = new RgbColor(0, 255, 255);
            element.setRgbColor(rgbColor);
            mFloatGroupLayout.setBackground(element);
        }
    }

    private class MyScrolledListener implements Component.ScrolledListener {

        @Override
        public void onContentScrolled(Component component, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            if (mIsRemoveItem) {
                mIsRemoveItem = false;
                //优化部分场景，防止重复计算
                if (scrollY > oldScrollY) {
                    return;
                }
            }
            int visibleIndex = mListContainer.getFirstVisibleItemPosition();
//                Utils.debug("onContentScrolled visibleIndex = " + visibleIndex);
            if (visibleIndex == 0) {
                Component firstVisibleItemView = mListContainer.getComponentAt(0);
                if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                    Utils.debug("##### 滚动到顶部 ######");
                    mHasHeader = false;
                    setHeaderVisibility(Component.HIDE);
                    return;
                }
            }
            //判断是否存在父控件，存在则显示，不存在继续隐藏
            if (mModelList.size() > 0) {
                refreshHeader(visibleIndex);
            }
        }
    }

    private void refreshHeader(int visibleIndex) {
        mHasHeader = false;
        ItemModel headerModel = null;
        if (mModelList.get(visibleIndex).isHeader()) {
            mHasHeader = true;
            headerModel = mModelList.get(visibleIndex);
        } else {
            for (int j = visibleIndex - 1; j >= 0; j--) {
                if (mModelList.get(j).isHeader()) {
                    mHasHeader = true;
                    headerModel = mModelList.get(j);
                    break;
                }
            }
        }

        if (mHasHeader) {
            String title = headerModel.getTitle();
            int[] padding = headerModel.getPaddings();
            getUITaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    mTvTitle.setText(title);
                    //TODO Text控件存在bug，值设置了，显示的不对
//                                Utils.debug("onContentScrolled title = " + title + ", getText = " + mTvTitle.getText());
                    mTvTitle.setPadding(padding[0], padding[1], padding[2], padding[3]);
                    setHeaderVisibility(Component.VISIBLE);
                }
            });

        } else {
            setHeaderVisibility(Component.HIDE);
        }
    }

    public void setHeaderVisibility(int visibility) {
        if (mFloatGroupLayout.getVisibility() != visibility) {
            mFloatGroupLayout.setVisibility(visibility);
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public Object onEventTransmission(Object target, Object params, int eventId, CallBack callBack) {
        mIsRemoveItem = true;
        mModelList.remove((int) params);
        mUltimateProvider.setModels(mModelList);
        return null;
    }

    private void jumpAbility() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.brandongogetap.stickyheaders.demo")
                .withAbilityName("com.brandongogetap.stickyheaders.demo.ViewPagerAbility")
                .build();
        intent.setOperation(operation);
        startAbility(intent);
        terminateAbility();
    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        terminateAbility();
    }
}
